package com.wzh.navcode.strategy;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.wzh.navcode.domain.entity.HotData;
import com.wzh.navcode.domain.vo.BaiDuHotTopic;
import com.wzh.navcode.service.CrawlStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangzhenghai
 * description: 百度热搜策略
 * @version 1.0
 */
@Service("baiduStrategy")
@Slf4j
public class BaiduCrawlStrategy implements CrawlStrategy {

    private static final String BAIDU_URL = "https://api.it8.com.cn/baidu";

    @Override
    public List<HotData> crawl() {
        String json = HttpUtil.get(BAIDU_URL);
        Object o = JSONUtil.parseObj(json).get("data");
        List<BaiDuHotTopic> list = JSONUtil.parseArray(o).toList(BaiDuHotTopic.class);
        List<HotData> hotDataList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        String formattedTime = LocalDateTime.now().format(formatter);
        for (BaiDuHotTopic hotTopic : list) {
            hotDataList.add(
                    HotData.builder()
                            .title(hotTopic.getTitle())
                            .url(hotTopic.getUrl())
                            .hotValue(String.format("%.1f万", hotTopic.getHot() / 10000.0))
                            .crawlTime("今天" + formattedTime)
                            .platform("百度")
                            .build());
        }
        return hotDataList.subList(0,10);
    }
}